<template>
  <div class="content-area">
    <!-- 时间筛选 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">统计时间</div>
          <el-date-picker
            v-model="timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="loadStatisticsData"
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">统计类型</div>
          <el-select
            v-model="statsType"
            placeholder="请选择统计类型"
            @change="loadStatisticsData"
          >
            <el-option label="日报表" value="daily" />
            <el-option label="周报表" value="weekly" />
            <el-option label="月报表" value="monthly" />
            <el-option label="年报表" value="yearly" />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">科室筛选</div>
          <el-select
            v-model="selectedDepartment"
            placeholder="请选择科室"
            clearable
            @change="loadStatisticsData"
          >
            <el-option
              v-for="dept in departmentOptions"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </div>
      </div>
      <div class="action-buttons">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" @click="loadStatisticsData">
          <el-icon><Search /></el-icon>
          查询
        </el-button>
        <el-button type="success" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="warning" @click="printReport">
          <el-icon><Printer /></el-icon>
          打印报表
        </el-button>
      </div>
    </div>

    <!-- 核心指标卡片 -->
    <div class="stats-cards">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon total">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">
                {{ formatNumber(stats.totalPatients) }}
              </div>
              <div class="stat-label">就诊人数</div>
              <div class="stat-trend">
                <span :class="getTrendClass(stats.patientTrend)">
                  <el-icon :name="getTrendIcon(stats.patientTrend)"></el-icon>
                  {{ Math.abs(stats.patientTrend) }}%
                </span>
                较上月
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon revenue">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">
                ¥{{ formatAmount(stats.totalRevenue) }}
              </div>
              <div class="stat-label">总收入</div>
              <div class="stat-trend">
                <span :class="getTrendClass(stats.revenueTrend)">
                  <el-icon :name="getTrendIcon(stats.revenueTrend)"></el-icon>
                  {{ Math.abs(stats.revenueTrend) }}%
                </span>
                较上月
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon avg">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ formatAmount(stats.avgBill) }}</div>
              <div class="stat-label">平均账单</div>
              <div class="stat-trend">
                <span :class="getTrendClass(stats.avgBillTrend)">
                  <el-icon :name="getTrendIcon(stats.avgBillTrend)"></el-icon>
                  {{ Math.abs(stats.avgBillTrend) }}%
                </span>
                较上月
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon rate">
              <el-icon><Success /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.satisfactionRate }}%</div>
              <div class="stat-label">满意度</div>
              <div class="stat-trend">
                <span :class="getTrendClass(stats.satisfactionTrend)">
                  <el-icon
                    :name="getTrendIcon(stats.satisfactionTrend)"
                  ></el-icon>
                  {{ Math.abs(stats.satisfactionTrend) }}%
                </span>
                较上月
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="16">
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>就诊人数趋势</h3>
              <el-select
                v-model="patientChartType"
                size="small"
                style="width: 120px"
              >
                <el-option label="折线图" value="line" />
                <el-option label="柱状图" value="bar" />
              </el-select>
            </div>
            <div class="chart-container" style="height: 300px">
              <MedicalVisitTrendLine v-if="patientChartType === 'line'" />
              <MedicalVisitTrendBar v-else />
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>收入构成分析</h3>
              <el-select
                v-model="revenueChartType"
                size="small"
                style="width: 120px"
              >
                <el-option label="饼图" value="pie" />
                <el-option label="环形图" value="doughnut" />
              </el-select>
            </div>
            <div class="chart-container" style="height: 300px">
              <RevenuePieChart v-if="revenueChartType === 'pie'" />
              <RevenueDoughnutChart v-else />
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="16" style="margin-top: 16px">
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>科室就诊量排名</h3>
            </div>
            <div class="chart-container" style="height: 300px">
              <DepartmentRankingChart />
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>医生工作量统计</h3>
            </div>
            <div class="chart-container" style="height: 300px">
              <DoctorWorkloadChart />
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="data-table">
      <div class="table-header">
        <div class="table-title">详细数据</div>
        <div class="table-tabs">
          <el-radio-group v-model="activeTableTab">
            <el-radio-button label="daily">日数据</el-radio-button>
            <el-radio-button label="department">科室数据</el-radio-button>
            <el-radio-button label="doctor">医生数据</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        stripe
        v-loading="tableLoading"
      >
        <el-table-column
          prop="date"
          label="日期"
          width="120"
          v-if="activeTableTab === 'daily'"
        />
        <el-table-column
          prop="department"
          label="科室"
          width="120"
          v-if="activeTableTab !== 'doctor'"
        />
        <el-table-column
          prop="doctor"
          label="医生"
          width="120"
          v-if="activeTableTab === 'doctor'"
        />
        <el-table-column
          prop="patientCount"
          label="就诊人数"
          width="100"
          align="center"
        />
        <el-table-column
          prop="revenue"
          label="收入(元)"
          width="120"
          align="right"
        >
          <template #default="{ row }">
            ¥{{ formatAmount(row.revenue) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="avgBill"
          label="平均账单"
          width="120"
          align="right"
        >
          <template #default="{ row }">
            ¥{{ formatAmount(row.avgBill) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="drugRevenue"
          label="药品收入"
          width="120"
          align="right"
        >
          <template #default="{ row }">
            ¥{{ formatAmount(row.drugRevenue) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="checkRevenue"
          label="检查收入"
          width="120"
          align="right"
        >
          <template #default="{ row }">
            ¥{{ formatAmount(row.checkRevenue) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="treatmentRevenue"
          label="治疗收入"
          width="120"
          align="right"
        >
          <template #default="{ row }">
            ¥{{ formatAmount(row.treatmentRevenue) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="satisfaction"
          label="满意度"
          width="100"
          align="center"
        >
          <template #default="{ row }"> {{ row.satisfaction }}% </template>
        </el-table-column>
        <el-table-column label="趋势" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.trend >= 0 ? 'success' : 'danger'" size="small">
              <el-icon :name="row.trend >= 0 ? 'Top' : 'Bottom'"></el-icon>
              {{ Math.abs(row.trend) }}%
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
// 引入统计组件
import MedicalVisitTrendLine from "@/components/manager/echarts/MedicalVisitTrendLine.vue";
import MedicalVisitTrendBar from "@/components/manager/echarts/MedicalVisitTrendBar.vue";
import RevenuePieChart from "@/components/manager/echarts/RevenuePieChart.vue";
import RevenueDoughnutChart from "@/components/manager/echarts/RevenueDoughnutChart.vue";
import DepartmentRankingChart from "@/components/manager/echarts/DepartmentRankingChart.vue";
import DoctorWorkloadChart from "@/components/manager/echarts/DoctorWorkloadChart.vue";

const sidebarOpen = ref(false);
const router = useRouter();
const store = useStore();

const username = ref(store.state.user?.username || "管理员");

// 筛选条件
const timeRange = ref([getDateString(-30), getDateString(0)]);
const statsType = ref("daily");
const selectedDepartment = ref("");

// 图表类型
const patientChartType = ref("line");
const revenueChartType = ref("pie");

// 表格数据
const activeTableTab = ref("daily");
const tableLoading = ref(false);
const tableData = ref([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 科室选项
const departmentOptions = [
  { value: "D001", label: "内科" },
  { value: "D002", label: "外科" },
  { value: "D003", label: "儿科" },
  { value: "D004", label: "妇产科" },
  { value: "D005", label: "眼科" },
  { value: "D006", label: "耳鼻喉科" },
  { value: "D007", label: "口腔科" },
  { value: "D008", label: "皮肤科" },
  { value: "D009", label: "急诊科" },
  { value: "D010", label: "检验科" },
  { value: "D011", label: "影像科" },
];

// 统计数据
const stats = reactive({
  totalPatients: 12458,
  totalRevenue: 3568420.5,
  avgBill: 286.35,
  satisfactionRate: 94.8,
  patientTrend: 12.5,
  revenueTrend: 8.3,
  avgBillTrend: -2.1,
  satisfactionTrend: 1.2,
});

// 获取日期字符串
function getDateString(daysOffset) {
  const date = new Date();
  date.setDate(date.getDate() + daysOffset);
  return date.toISOString().split("T")[0];
}

// 加载统计数据
const loadStatisticsData = () => {
  tableLoading.value = true;

  // 模拟数据加载延迟
  setTimeout(() => {
    // 生成模拟表格数据
    const mockData = [];
    const startDate = new Date(timeRange.value[0]);
    const endDate = new Date(timeRange.value[1]);
    const daysDiff = Math.floor((endDate - startDate) / (1000 * 60 * 60 * 24));

    for (let i = 0; i < Math.min(daysDiff, 30); i++) {
      const date = new Date(startDate);
      date.setDate(date.getDate() + i);

      mockData.push({
        date: date.toISOString().split("T")[0],
        department: "内科",
        doctor: "张医生",
        patientCount: Math.floor(Math.random() * 50) + 30,
        revenue: Math.floor(Math.random() * 20000) + 10000,
        avgBill: Math.floor(Math.random() * 200) + 200,
        drugRevenue: Math.floor(Math.random() * 8000) + 4000,
        checkRevenue: Math.floor(Math.random() * 6000) + 3000,
        treatmentRevenue: Math.floor(Math.random() * 6000) + 2000,
        satisfaction: Math.floor(Math.random() * 10) + 90,
        trend: Math.floor(Math.random() * 20) - 10,
      });
    }

    tableData.value = mockData;
    pagination.total = mockData.length;
    tableLoading.value = false;

    ElMessage.success("数据加载成功");
  }, 1000);
};

// 重置筛选条件
const resetFilters = () => {
  timeRange.value = [getDateString(-30), getDateString(0)];
  statsType.value = "daily";
  selectedDepartment.value = "";
  loadStatisticsData();
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  loadStatisticsData();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadStatisticsData();
};

// 导出数据
const exportData = () => {
  ElMessage.success("数据导出成功");
};

// 打印报表
const printReport = () => {
  ElMessage.info("打印功能准备中");
};

// 格式化金额
const formatAmount = (amount) => {
  return Number(amount)
    .toFixed(2)
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 格式化数字
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 获取趋势样式
const getTrendClass = (trend) => {
  return trend >= 0 ? "trend-up" : "trend-down";
};

// 获取趋势图标
const getTrendIcon = (trend) => {
  return trend >= 0 ? "Top" : "Bottom";
};

// 退出登录
const logout = () => {
  ElMessageBox.confirm("确定要退出登录吗？", "退出确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      router.push("/login");
      ElMessage.success("已退出登录");
    })
    .catch(() => {
      ElMessage.info("已取消退出");
    });
};

// 切换侧边栏
const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value;
};

onMounted(() => {
  loadStatisticsData();
});
</script>

<style lang="scss" scoped>
.content-area {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  height: 0; // 添加这行
  min-height: 100%; // 添加这行
  overflow-y: auto; // 确保有这行
}

.filter-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  flex: 1;
  min-width: 200px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 16px;
  font-size: 24px;
  color: #fff;
}

.stat-icon.total {
  background: linear-gradient(135deg, #409eff, #79bbff);
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #67c23a, #b3e19d);
}

.stat-icon.avg {
  background: linear-gradient(135deg, #e6a23c, #f3d19e);
}

.stat-icon.rate {
  background: linear-gradient(135deg, #f56c6c, #fab6b6);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-trend {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

.charts-section {
  margin-bottom: 24px;
}

.chart-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  border-radius: 6px;
  border: 1px dashed #dcdfe6;
}

.chart-placeholder {
  text-align: center;
  color: #909399;
}

.chart-placeholder .el-icon {
  font-size: 48px;
  margin-bottom: 8px;
}

.chart-placeholder p {
  margin: 0;
  font-size: 14px;
}

.data-table {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
  }

  .filter-item {
    min-width: 100%;
  }

  .stats-cards .el-col {
    margin-bottom: 16px;
  }

  .charts-section .el-col {
    margin-bottom: 16px;
  }

  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>